# encoding:utf-8

import json
from datetime import timedelta

import openai
from flask import Flask, request, render_template, make_response, Response

from server import auth, chatModel
from server.chatModel import Chat

user_session = dict()

requestMapping = Flask(__name__, template_folder='../templates', static_folder='../static', static_url_path='/static')
# 自动重载模板文件
requestMapping.jinja_env.auto_reload = True
requestMapping.config['TEMPLATES_AUTO_RELOAD'] = True

# 设置静态文件缓存过期时间
requestMapping.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
requestMapping.config["REDIS_URL"] = "redis://localhost:6379/0"


@requestMapping.route('/chat', methods=['POST', 'GET'])
async def asyncChat():
    # 从请求中获取用户输入的消息
    message = request.args.get('msg')
    id = request.args.get('id')
    data = dict()
    data["id"] = id
    data["msg"] = message
    context = dict()
    context['from_user_id'] = str(id)
    return Response(Chat().reply(message, context), content_type="text/event-stream")


@requestMapping.route('/chatText', methods=['POST', 'GET'])
def chat():
    message = request.args.get('msg')
    id = request.args.get('id')
    result = {"success": True, "data": Chat().reply_text(message, id), "msg": ""}
    response = make_response(json.dumps(result), 200)
    response.headers.add_header('content-type', 'application/json;charset=UTF-8')
    return response


@requestMapping.route("/", methods=['GET', 'POST'])
def index():
    if (auth.identify(request) == False):
        return login()
    return render_template('index.html')


@requestMapping.route("/login", methods=['POST', 'GET'])
def login():
    response = make_response("<html></html>", 301)
    response.headers.add_header('content-type', 'text/plain')
    response.headers.add_header('location', './')
    if (auth.identify(request) == True):
        return response
    else:
        if request.method == "POST":
            token = auth.authenticate(request.form['password'])
            if (token != False):
                response.set_cookie(key='Authorization', value=token)
                return response
        else:
            return render_template('new.html')
    response.headers.set('location', './login?err=登录失败')
    return response


@requestMapping.route("/checkAuth", methods=['POST'])
def checkAuth():
    result = {"success": True, "data": None, "msg": ""}
    response = make_response(json.dumps(result), 200)
    response.headers.add_header('content-type', 'application/json;charset=UTF-8')
    if (auth.identify(request) == False):
        token = auth.authenticate(request.form['password'])
        if (token):
            response.set_cookie(key='Authorization', value=token)
            response.headers.set('location', '/')
            response.headers.add_header('content-type', 'text/plain')
        else:
            result["msg"] = "密码错误"
            result["success"] = False
            response = make_response(json.dumps(result), 200)
    return response


class HttpController:
    def startUp(self):
        requestMapping.run(host='0.0.0.0', port=9845)
